package falcon.common;

import java.util.ArrayList;
import java.util.List;

public final class FalconConfig {
	
	public static final class Key {
		public static final String HOST = "host";
		public static final String PORT = "port";
		public static final String DIR = "dir";
		public static final String SSH_USER = "ssh.user";
		public static final String SSH_PORT = "ssh.port";
	}
	
	public FalconConfig(String path) {
		m_hostList = new ArrayList<String>();
		String[] lines = TextFile.readLines(path);
		if (lines == null) {
			return;
		}
		for (int i = 0; i < lines.length; i ++) {
			String line = lines[i];
			parseLine(line);
		}
	}
	
	public List<String> getHostList() {
		return m_hostList;
	}
	
	public int getPort() {
		return m_port;
	}
	
	public String getDir() {
		return m_dir;
	}
	
	public String getSshUser() {
		return m_sshUser;
	}
	
	public int getSshPort() {
		return m_sshPort;
	}
	
	private void parseLine(String line) {
		ArrayList<String> list = null;
		if (line.startsWith(FalconConfig.Key.HOST)) {
			list = m_hostList;
		} else if (line.startsWith(FalconConfig.Key.PORT)) {
			m_port = parseInt(line);
		} else if (line.startsWith(FalconConfig.Key.DIR)) {
			m_dir = parseStr(line);
		} else if (line.startsWith(FalconConfig.Key.SSH_USER)) {
			m_sshUser = parseStr(line);
		} else if (line.startsWith(FalconConfig.Key.SSH_PORT)) {
			m_sshPort = parseInt(line);
		}
		if (list == null) {
			return;
		}
		String value = parseStr(line);
		if (value == null || list.contains(value)) {
			return;
		}
		list.add(value);
	}
	
	private static String parseStr(String line) {
		String[] array = line.split("=");
		if (array.length != 2) {
			Log.log("array.length != 2;line=%s", line);
			return null;
		}
		String value = array[1].trim();
		return value;
	}
	
	private static int parseInt(String line) {
		String value = parseStr(line);
		if (value == null) {
			return 0;
		}
		int v = 0;
		try {
			v = Integer.parseInt(value);
		} catch (Exception e) {
			v = 0;
			Log.log(e, "parseInt failure;line=%s", line);
		}
		return v;
	}
	
	private int m_port;
	private String m_dir;
	private String m_sshUser;
	private int m_sshPort;
	private ArrayList<String> m_hostList;
}
